import * as React from 'react';
import { useCallback, useEffect, useState } from 'react';
import { RechargeRecordsResponse } from 'admin/schema/EnterpriseBill';
import { getCompanyRechargeRecord } from 'admin/servers/servers';
import { Button, DatePicker, Form, Space, Table } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import moment from 'moment';
import { clearNull } from 'utils/tools';
import { debounce } from 'lodash';
import { useHistory, useLocation } from 'react-router-dom';
import store from 'store';
import { RangeValue } from './components/MonthBill';
import './style.scss';

export enum RechargeTypes {
  '全部' = 0,
  '后台充值' = 1,
}

/**日账单 */
const RechargeRecord: React.FC = () => {
  const history = useHistory();
  const location = useLocation<any>();
  const { type } = location.state;
  const { companyId } = store.getState().userInfo;

  const { RangePicker } = DatePicker;
  const timeFormat = 'YYYY-MM-DD';

  /**默认时间段：无限制*/
  const defaultTime = null;

  // 时间相关
  const [timeHackValue, setTimeHackValue] = useState<RangeValue>(null);
  const [timeValue, setTimeValue] = useState<RangeValue>(defaultTime); // 时间值

  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);

  const [tableData, setTableData] = useState<RechargeRecordsResponse>();
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);

  const [reset, setReset] = useState<boolean>(false);

  /**Table列描述数据对象 */
  const columns: ColumnsType<RechargeRecordsResponse[0]> = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
      width: 100,
    },
    {
      title: '充值时间',
      dataIndex: 'rechargeTime',
    },
    {
      title: '充值金额（元）',
      dataIndex: 'rechargeAmount',
    },
    {
      title: '充值方式',
      dataIndex: 'rechargeMode',
      render: (text, record, index) => RechargeTypes[text],
    },
    {
      title: '操作人',
      dataIndex: 'operator',
    },
  ];

  /**
   * 查询table数据
   */
  const fetchTable = useCallback(async () => {
    setTableLoading(true);
    try {
      const param = {
        pageNo: current,
        pageSize: pageSize,
        beginTime: timeValue ? moment(timeValue[0]).format(timeFormat) : undefined,
        endTime: timeValue ? moment(timeValue[1]).format(timeFormat) : undefined,
        companyId,
      };
      console.log('param===', param);
      const res = await getCompanyRechargeRecord(clearNull(param));
      const { data = [], count = 0 } = res;
      setTableData(data);
      setTotal(count);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [companyId, current, pageSize, timeValue]);

  // 页面初始化
  useEffect(() => {
    console.log('recharge render state=', type);
    setReset(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (reset) {
      fetchTable();
      setReset(false);
    }
  }, [fetchTable, reset]);

  /**操作：搜索 */
  const handleSearch = debounce(() => {
    if (current !== 1) {
      setCurrent(1);
    }
    setReset(true);
  }, 500);

  /**操作：重置为默认值 */
  const handleReset = debounce(() => {
    setTimeValue(defaultTime);
    setReset(true);
  }, 500);

  const onOpenChange = (open: boolean) => {
    if (open) {
      setTimeHackValue([null, null]);
    } else {
      setTimeHackValue(null);
    }
  };

  const handleBack = () => {
    history.push(`/webapp/enterpriseBill/${type}`);
  };

  return (
    <div className="enterprise-bill">
      <div className="main-wrap">
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Form layout="inline">
              <Form.Item label="充值日期">
                <RangePicker
                  format={timeFormat}
                  value={timeHackValue || timeValue}
                  onChange={val => setTimeValue(val)}
                  onOpenChange={onOpenChange}
                />
              </Form.Item>
              <Space size="middle">
                <Button type="primary" onClick={handleSearch}>
                  搜索
                </Button>
                <Button type="primary" ghost onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Form>
          </div>
          <div className="mgr-header-right">
            <Button onClick={handleBack}>返回</Button>
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            columns={columns}
            dataSource={tableData}
            rowKey="rechargeRecordId"
            pagination={{
              current: current,
              total: total,
              pageSize: pageSize,
              showSizeChanger: true,
              // 改条数/页
              onShowSizeChange: (current, size) => {
                setPageSize(size);
                setReset(true);
              },
              // 改页码
              onChange: current => {
                setCurrent(current);
                setReset(true);
              },
              showTotal: total => `共${total}条`,
            }}
          />
        </div>
      </div>
    </div>
  );
};

export default RechargeRecord;
